/**
 * Created by czf on 2015/4/16.
 */

var GlobalError = require('../../utils/GlobalError');
var timeUtils = require('../../utils/TimeUtils');
var TimeTask = require('../../utils/TimeTask');
var phoneUtils = require('../../utils/PhoneUtils');
var moment = require('moment');
var _ = require('underscore');
module.exports = function (server) {

  var task_phone = server.models.task_phone;

  /**
   * 保存记录
   * http://localhost:3001/taskPhone/save/13928720730/13928720730/2015-01-04%2008:08:08/1/4/1,2
   */
  server.use('/taskPhone/save/:phone/:targetPhone/:setTime/:state/:repeat/:weeks', function (req, res) {


    var phone = req.params.phone;
    var targetPhone = req.params.targetPhone;

    if (!phoneUtils.isMobile(phone)) {
      return GlobalError.throwErrorMsg("主拨打电话格式输入有误", res)
    }

    if (!phoneUtils.isMobile(targetPhone)) {
      return GlobalError.throwErrorMsg("拨打的电话格式输入有误", res)
    }

    var setTime = req.params.setTime;

    if (!timeUtils.isValidDateTime(setTime)) {
      return GlobalError.throwErrorMsg("执行时间格式错误(如:yyyy-MM-dd HH:mm:ss)", res)
    }
    var repeat = req.params.repeat;
    var weeks = req.params.weeks;
    //如果设置周重复，验证填写周重复信息是否符合规范，1,2,3,4,5,6,7  已逗号分割，1是星期一
    if (repeat == 4) {//4代表周重复
      var re = /^([1-7](,{1})){0,6}[1-7]{1}$/i;
      if (!re.test(weeks)) {
        return GlobalError.throwErrorMsg("周重复格式错误(如:1,2,3,4,5,6,7)", res)
      }
    } else {
      weeks = 0;
    }

    var model = new task_phone();
    model.phone = phone;
    model.targetPhone = targetPhone;
    model.setTime = setTime;
    model.excTime = TimeTask.getNextExcTime(setTime , repeat , weeks);
    model.state = req.params.state;
    model.repeat = repeat;
    model.weeks = weeks;
    model.createTime = new Date();
    //{
    //  "phone": "13928720730",
    //  "targetPhone": "13928720730",
    //  "excTime": "2013-12-31T16:00:00.000Z",
    //  "setTime": "2013-12-31T16:00:00.000Z",
    //  "repeat": 0,//是否要重复
    //  "weeks": "",//周重复1,2,3
    //  "state": 0,//是否有效
    //  "createTime": "2013-12-31T16:00:00.000Z"
    //}
    task_phone.saveModel(model, function (err, data) {
      if (err) return GlobalError.throwErrorMsg("保存出错", res);
      res.json(data[0]);
    });
  });

  /**
   * 根据id删除记录
   * http://localhost:3001/taskPhone/delById/10
   */
  server.use('/taskPhone/delById/:id', function (req, res) {

    var id = req.params.id;

    if (!_.isFinite(id)) {
      return GlobalError.throwErrorMsg("id输入有误", res)
    }

    task_phone.delById(id, function (flag) {
      res.json(flag);
    });
  });


  /**
   * 根据主拨手机号码，获取记录
   * http://localhost:3001/taskPhone/getList/13928720730
   */
  server.use('/taskPhone/getList/:phone', function (req, res) {

    var phone = req.params.phone;

    task_phone.getList(phone, function (err, models) {
      res.json(models);
    });
  });

  /**
   * 停止拨打电话任务
   * http://localhost:3001/taskPhone/stopTaskById/1
   */
  server.use('/taskPhone/stopTaskById/:id', function (req, res) {

    var id = req.params.id;

    if (!_.isFinite(id)) {
      return GlobalError.throwErrorMsg("id输入有误", res)
    }
    //获取数据
    task_phone.findModelById(id, function (err, data) {
      if (data == null) {
        return GlobalError.throwErrorMsg("找不到数据", res);
      }
      var model = data.__data;
      model.state = 0;//设置为停用
      //更新数据
      task_phone.updModel(model, function (err, newModel) {
        if (err) return GlobalError.throwErrorMsg("修改出错", res);
        res.json(newModel);
      });
    });
  });


  /**
   * 开启拨打电话服务
   * http://localhost:3001/taskPhone/startTaskById/1
   */
  server.use('/taskPhone/startTaskById/:id', function (req, res) {

    var id = req.params.id;

    if (!_.isFinite(id)) {
      return GlobalError.throwErrorMsg("id输入有误", res)
    }
    //获取数据
    task_phone.findModelById(id, function (err, data) {
      if (data == null) {
        return GlobalError.throwErrorMsg("找不到数据", res);
      }
      var model = data.__data;
      model.state = 1;//设置为启用
      //更新数据
      task_phone.updModel(model, function (err, newModel) {
        if (err) return GlobalError.throwErrorMsg("修改出错", res);
        res.json(newModel);
      });
    });
  });

  /**
   * 添加或者修改记录修改记录
   * :id 0时添加记录  大于零是修改记录
   * http://localhost:3001/taskPhone/createOrupdate/0/13928720730/13928720730/2015-01-04%2008:08:08/1/1/1,2
   */
  server.use('/taskPhone/createOrupdate/:id/:phone/:targetPhone/:setTime/:state/:repeat/:weeks', function (req, res) {

    var id = req.params.id;

    if (!_.isFinite(id)) {
      return GlobalError.throwErrorMsg("id输入有误", res)
    }

    var phone = req.params.phone;
    var targetPhone = req.params.targetPhone;

    if (!phoneUtils.isMobile(phone)) {
      return GlobalError.throwErrorMsg("主拨打电话格式输入有误", res)
    }

    if (!phoneUtils.isMobile(targetPhone)) {
      return GlobalError.throwErrorMsg("拨打的电话格式输入有误", res)
    }

    var setTime = req.params.setTime;

    if (!timeUtils.isValidDateTime(setTime)) {
      return GlobalError.throwErrorMsg("执行时间格式错误(如:yyyy-MM-dd HH:mm:ss)", res)
    }

    var repeat = req.params.repeat;
    if (!_.isFinite(repeat)) {
      return GlobalError.throwErrorMsg("id输入有误", res)
    }
    //转换为数字类型
    repeat = Number(repeat);
    var weeks = req.params.weeks;
    //如果设置周重复，验证填写周重复信息是否符合规范，1,2,3,4,5,6,7  已逗号分割，1是星期一
    //类型:0不重复，1天重复，2月重复，3年重复，4周重复
    if (repeat == 4 ) {//4代表周重复
      var re = /^([1-7](,{1})){0,6}[1-7]{1}$/i;
      if (!re.test(weeks)) {
        return GlobalError.throwErrorMsg("周重复格式错误(如:1,2,3,4,5,6,7)", res)
      }
    } else {
      weeks = 0;
    }

    var model = new task_phone();
    model.id = id;
    model.phone = phone;
    model.targetPhone = targetPhone;
    model.setTime = setTime;
    //console.log(timeUtils.format(TimeTask.getNextExcTime(setTime , repeat , weeks)));
    model.excTime = TimeTask.getNextExcTime(setTime , repeat , weeks);
    model.state = req.params.state;
    model.repeat = repeat;
    model.weeks = weeks;
    model.createTime = new Date();

    task_phone.updModel(model, function (err, data) {
      if (err) {
        return GlobalError.throwErrorMsg("出错", res);
      }
      res.json(task_phone.coverTime(data));
    });
  });


  server.use('/taskPhone/exc', function (req, res) {

    var array = new Array();

    //获取要执行的任务列表
    task_phone.getExcList(function (err, models) {

      if (models != null && _.isArray(models)) {
        _.each(models, function (item, index) {

          if(item.state == 1){
            //获取今天要执行的任务
            var excTime = TimeTask.getNextExcTimeInToday(item.excTime || item.setTime , item.repeat , item.weeks);

            //启动定时任务
            if(excTime != null){

              array.push(item.id);
              array.push(timeUtils.format4Moment(excTime));

              TimeTask.excTaskByDate(excTime , function(excFlag , exctask){

                if(excFlag){
                  console.log('定时任务执行了');
                }

              });
            }
          }

        });
      }
      res.json(array);
    });
  });

}
